/*
 *  Copyright 2012 Yuriy Dunko.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.pc.domain.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

import org.hibernate.FetchMode;
import org.hibernate.SQLQuery;
import org.hibernate.classic.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.opu.pc.domain.dao.PublisherDao;
import org.opu.pc.domain.domains.Publication;
import org.opu.pc.domain.domains.Publisher;

/**
 *
 * @author Yuriy Dunko
 */
public class PublisherDaoImpl extends AbstractHibernateDao<Integer, Publisher>
		implements PublisherDao, CriteriaSpecification {

	@Override
	protected Class<Publisher> getDomainClass() {
		return Publisher.class;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Publisher> getPublishersByName(String name, String secondName,
			String lastName){
		DetachedCriteria criteria = DetachedCriteria.forClass(getDomainClass());
		criteria.add(Restrictions.eq("name", name));
		criteria.add(Restrictions.eq("secondName", secondName));
		criteria.add(Restrictions.eq("lastName", lastName));
		return hibernateTemplate.findByCriteria(criteria);
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Publisher> searchPublishersByName(String name, String secondName,
			String lastName){
		DetachedCriteria criteria = DetachedCriteria.forClass(getDomainClass());
		if (name != null && !name.isEmpty()) {
            criteria.add(Restrictions.like("name", name));
        }
		if (secondName != null && !secondName.isEmpty()) {
            criteria.add(Restrictions.like("secondName", secondName));
        }
		if (lastName != null && !lastName.isEmpty()) {
            criteria.add(Restrictions.like("lastName", lastName));
        }
		return hibernateTemplate.findByCriteria(criteria);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Publisher> searchPublishersByStudentBelonging(Boolean isSruden) {
		DetachedCriteria criteria = DetachedCriteria.forClass(getDomainClass());
		criteria.add(Restrictions.eq("isStudent", isSruden));
		return hibernateTemplate.findByCriteria(criteria);
	}
	
	@Override
	public List<Publisher> getPublishersForPublication(Publication publication){
		return getPublishersForPublication(publication.getId());
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Publisher> getPublishersForPublication(Integer publicationId){
		DetachedCriteria criterial = DetachedCriteria.forClass(getDomainClass());
		criterial.createAlias("publications", "publication")
				.setFetchMode("publications", FetchMode.JOIN);
		criterial.add(Restrictions.eq("publication.id", publicationId));
		return hibernateTemplate.findByCriteria(criterial);
	}

    @Override
    public void merge(Integer publisherEtalonId, List<Integer> publisherDuplicatsId) {
        Session session = hibernateTemplate.getSessionFactory().openSession();

        SQLQuery query = session.createSQLQuery(
                "UPDATE publication_publicators " +
                "SET publicators_id=? " +
                "WHERE publicators_id IN (:list)");
        query.setParameter(0, publisherEtalonId);
        query.setParameterList("list", publisherDuplicatsId);
        query.executeUpdate();

        query = session.createSQLQuery(
                "DELETE FROM publisher " +
                "WHERE id IN (:list)");
        query.setParameterList("list", publisherDuplicatsId);
        query.executeUpdate();

        session.disconnect();
    }

    @Override
	@SuppressWarnings("unchecked")
    public List<Publisher> getPublishersWithPublications(Date start, Date end,
            Boolean isStudent, Boolean isVac) {
    	
    	DetachedCriteria criteria = DetachedCriteria.forClass(getDomainClass());
    	if (isStudent != null){
    		criteria.add(Restrictions.eq("isStudent", isStudent));
    	}
    	criteria.addOrder(Order.asc("secondName"));
    	criteria.addOrder(Order.asc("name"));
    	criteria.addOrder(Order.asc("lastName"));
    	
    	criteria.createAlias("publications", "publication", LEFT_JOIN);
    	criteria.add(Restrictions.between("publication.date", start, end));
    	if (isVac != null){
    		criteria.add(Restrictions.eq("publication.wasApplied", isVac));
    	}
    	criteria.addOrder(Order.asc("publication.date"));
    	
    	criteria.createAlias("publication.publishers", "publisher", LEFT_JOIN);
    	
    	// Return unique set
    	return new ArrayList<Publisher>(new LinkedHashSet<Publisher>(
    			hibernateTemplate.findByCriteria(criteria)));
    }

}